<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 管理员
 * @author www.dingwei.cn
 */
class User extends MY_Controller {
    public $mUser=null; //临时定义一个 待删除
    public $mRole=null; //临时定义一个 待删除

    /**
     * 初始化
     * User constructor.
     */

    public function __construct() {
        parent::__construct();
        $this->loadModel('AdmUserModel', 'mUser');
        $this->loadModel('AdmRoleModel', 'mRole');
    }
    
	/**
	 * 首页
	 */
	public function index(){
	    $role = $this->mRole->getAllList();

		$this->view('setting/user/user',array('title'=>'管理员','role' => $role), 'datatable');
	}

    /**
     * 管理员编辑
     */
    public function edit(){
        if($_POST){
            $this->_save();
        }
        $this->loadModel('AdmRoleModel', 'mRole');
        $admin = $this->mUser->getAdmin($this->input->get('id'));
        $data = array(
        			'is_add' => false,
	            	'admin'=>$admin,
                    'role' => $this->mRole->getAllList()
        );

        $this->view('setting/user/save', $data, 'validation,select2,uniform');
    }
    
    /**
     * 保存数据
     */
    private function _save(){
    	
    	//表单验证
    	$vConf = array(
    			array('name', '姓名', 'required|max_length[10]'),
    			array('account', '登录账户', 'required'),
    			array('password', '登录密码', 'min_length[6]|max_length[15]'),
    			array('repassword', '确认密码', 'matches[password]'),
    	);
    	
    	$this->formDataValidation($vConf);
    	$id = $this->input->post('id');
    	$name = $this->input->post('name');
    	$account = $this->input->post('account');
    	$password = $this->input->post('password');
    	$type = (int)$this->input->post('type');
    	$role_id = (int)$this->input->post('role_id');
    	if( ! in_array($type, array(0,1))){
    		$this->ajaxReturn(0, '参数错误');
    	}

    	if($this->mUser->isAccount($account, $id)){
    		$this->ajaxReturn(0, '账号已经存在');
    	}
    	
    	$data = array(
    			'account' => $account,
    			'name' => $name,
    			'type' => $type,
    			'admin_type' => $type,
    			'role_id' => $type == 1 ? 0:$role_id,
    	);
    	
    	if($password){
    		$data['password'] = setPassword($password);
    	}
    	
    	if( ! $id){
    		$data['addtime'] = time();
    		$data['status'] = 2;
    	}

    	if($this->mUser->save($data, $id)){
    		$this->ajaxReturn(1, '已保存', null, getUrl('setting/user'));
    	}
    	
    	$this->ajaxReturn(0, '保存失败');
    }

    /**
     * 添加管理员
     */
    public function add()
    {
        if($_POST){
           $this->_save();
        }
        $this->loadModel('AdmRoleModel', 'mRole');
       	$data = array(
       			   'is_add' => true,
            'role' => $this->mRole->getAllList()
 			     );
        $this->view('setting/user/save', $data,'validation,select2,uniform');
    }
	/**
	 * 列表
	 */
	public function getList(){
        $data=$this->mUser->getList();
        if( ! empty($data['data'])){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $v['name'];
                $data['aaData'][$k][] = $v['account'];
                $data['aaData'][$k][] = isset($v['role_name'])?$v['role_name']:'超级管理员';
                $data['aaData'][$k][] = date('Y-m-d', $v['addtime']);
                $status = $v['status'] == 1 ? 2 : 1;
                $data['aaData'][$k][] = adminCreateBtn(array(
                    'label' => $this->adminStatus($v['status'], true),
                    'attr' => array(
                        'href' => getUrl('setting/user/changeStatus?id='.$v['id'].'&status='.$status),
                        'alert-message' => "确认是否".$this->adminStatus($status)."？",
                        'class' => 'ajax-request-btn deco',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'setting',
                        'key' => 'user-status'
                    )
                ));
                $btnConfig = adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('setting/user/edit?id='.$v['id']),
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'setting',
                        'key' => 'user-edit'
                    )
                ));
                $btnConfig .= ' '. adminCreateBtn(array(
                    'label' => '删除',
                    'attr' => array(
                        'href' => getUrl('setting/user/delete?id='.$v['id']),
                        'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                        'alert-message'=>'确定删除管理员 “ '.$v['name'].' ” ?',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'setting',
                        'key' => 'user-delete'
                    )
                ));

                $data['aaData'][$k][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }
    /**
     * 删除管理员
     */
    public function delete(){
        $id = get('id');

        $info = $this->mUser->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '管理员不存在');
        }
        if($this->mUser->deleteUser($id)){
            $this->ajaxReturn(1, '删除成功');
        }

        $this->ajaxReturn(0, '删除失败');
    }

    /**
	 * 修改状态
	 */
    public function changeStatus(){
        $id = get('id');
        $status = (int)get('status');
        $info = $this->mUser->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '管理员不存在');
        }
        if($this->mUser->changeStatus($id, $status)){
        	$this->ajaxReturn(1, '已保存');
        }
        
        $this->ajaxReturn(0, '保存失败');
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case 0: $error  ='保存失败'; break;
            case -1: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }
}
